package org.ytor.core.sqlflow.builder.support;

import org.ytor.common.util.Strs;
import org.ytor.core.sqlflow.PersistenceModel;
import org.ytor.core.sqlflow.builder.AbsBuilder;
import org.ytor.core.sqlflow.builder.IOrderedParams;
import org.ytor.core.sqlflow.executor.DMLResult;
import org.ytor.core.sqlflow.executor.SQLRuntime;
import org.ytor.core.sqlflow.log.SqlLogHelper;
import org.ytor.core.sqlflow.plugin.Interceptor;
import org.ytor.core.sqlflow.plugin.InterceptorManager;

import java.util.List;
import java.util.function.Consumer;

/**
 * created by yangtong on 2025/8/8 10:44:25
 * <br/>
 * delete 构建, 惰性
 */
public class DeleteBuilder<T extends PersistenceModel<T, ?>> extends AbsBuilder implements IOrderedParams {

    /**
     * 表实体类
     */
    private Class<T> table;

    /**
     * 表名称
     */
    private String tableName;

    /**
     * WHERE 条件
     */
    private WhereBuilder where;

    public DeleteBuilder<T> from(Class<T> table) {
        this.table = table;
        this.tableName = getTableName(table);
        return this;
    }

    public DeleteBuilder<T> where(Consumer<WhereBuilder> consumer) {
        WhereBuilder builder = new WhereBuilder(null);
        consumer.accept(builder);
        this.where = builder;
        return this;
    }

    @Override
    public String toSql() {
        if (table == null) {
            SqlLogHelper.error("DELETE 缺少表, 请检查");
            throw new IllegalStateException("DELETE 缺少表，请检查");
        }
        String whereSql = (where == null) ? "" : where.toSql();
        return "DELETE FROM\n\t" + getTableName(table) + whereSql;
    }

    private String toInnerSql() {
        List<Interceptor> interceptors = InterceptorManager.interceptors();
        for (Interceptor interceptor : interceptors) {
            interceptor.beforeDeleteBuilder(table, tableName, where);
        }
        return toSql();
    }

    @Override
    public List<Object> orderedParams() {
        return (where == null) ? List.of() : where.orderedParams();
    }

    /**
     * 提交SQL执行
     */
    public DMLResult submit() {
        String whereSql = (where == null) ? "" : where.toSql();
        if (Strs.isEmpty(whereSql)) {
            SqlLogHelper.error("DELETE 缺少 WHERE 条件, 已拦截该全表删除操作");
            throw new IllegalStateException("DELETE 缺少 WHERE 条件, 已拦截该全表删除操作");
        }

        String sql = toInnerSql();
        // DELETE执行前
        List<Interceptor> interceptors = InterceptorManager.interceptors();
        for (Interceptor interceptor : interceptors) {
            interceptor.beforeDelete(table, tableName, sql, where, orderedParams());
        }

        DMLResult result = SQLRuntime.doDelete(sql, orderedParams());

        // DELETE执行后
        for (Interceptor interceptor : interceptors) {
            interceptor.afterDelete(table, tableName, sql, where, orderedParams(), result);
        }

        return result;
    }
}
